package xyz.canran.project.algorithm.zerocopy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Scanner;

/**
 * 内存映射零拷贝
 */
public class MemoryMapZeroCopy {


    private static final Logger log = LoggerFactory.getLogger(MemoryMapZeroCopy.class);

    public void zeroCopyConsole(String fileName) throws IOException {
        File file = new File(fileName);
        if (!file.exists()) {
            throw new FileNotFoundException(fileName);
        }

        long fileSize = file.length();
        int bufferSize = 1024 * 1024;
        if (fileSize < bufferSize) {
            bufferSize = (int) fileSize;
        }
        byte[] buffer = new byte[bufferSize];

        MappedByteBuffer mappedByteBuffer;
        try(FileInputStream fis = new FileInputStream(file);) {
            // 内存映射零拷贝， 此时 mappedByteBuffer 就是在虚拟内存建立一个映射关系， 目前是只读不可写
            mappedByteBuffer = fis.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, fileSize);

            // 内存映射零拷贝， 此时 mappedByteBuffer 就是在虚拟内存建立一个映射关系， 目前是可读写
            // mappedByteBuffer = fis.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, fileSize);
        } catch (FileNotFoundException e) {
            log.error("file not find", e);
            return;
        }

        for (int i = 0; i < buffer.length; i++) {
            byte b = mappedByteBuffer.get();
            buffer[i] = b;
        }

        Scanner scanner = new Scanner(new ByteArrayInputStream(buffer)).useDelimiter("\r\n");
        while (scanner.hasNext()) {
            String line = scanner.next();
            log.info("line:{}", line);
        }


    }
}
